// 图形校验码
const svgCaptcha = require('svg-captcha')
const NXlSX = require("node-xlsx");

class CommonControls {
    // 图片上传
    async uploadImage(ctx) {
        const file = ctx.request.files.file;
        const basename = path.basename(file.name)
        const reader = fs.createReadStream(file.path);
        const flag = fs.existsSync(path.join(__dirname, `../public/` + basename))
        let stream
        let index = 1
        if (flag) {
            const name = basename.slice(0, basename.lastIndexOf('.'))
            while (fs.existsSync(path.join(__dirname, `../public/${name}(${index}).jpg`))) {
                index++
            }
            const imageUrl = path.join(__dirname, `../public/${name}(${index}).jpg`)
            stream = fs.createWriteStream(imageUrl);
            reader.pipe(stream);
            ctx.body = {
                message: '图片上传成功',
                statusCode: 200,
                data: {
                    url: `${ctx.origin}/${name}(${index}).jpg`
                }
            }
        } else {
            stream = fs.createWriteStream(path.join(__dirname, `../public/` + basename));
            reader.pipe(stream);
            ctx.body = {
                message: '图片上传成功',
                statusCode: 200,
                data: {
                    url: `${ctx.origin}/${basename}`
                }
            }
        }
    }

    // 获取图形验证码
    getCaptcha(ctx) {
        const cap = svgCaptcha.create({
            size: 4, // 验证码长度
            width: 130,
            height: 40,
            fontSize: 50,
            ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1i
            noise: 2, // 干扰线条的数量
            color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
            background: '#eee' // 验证码图片背景颜色
        })
        ctx.body = {
            message: '获取验证码成功',
            statusCode: 200,
            data: {
                text: cap.text,
                data: cap.data
            }
        }

    }
    // excel 导入
    excelIn (ctx) {
        const file = ctx.request.files.file;
        const ex1 = NXlSX.parse(file.path) 
        ctx.body = {
            data: ex1
        }
    }
    
    // excel 导出
    excelOut (ctx){
        const _headers = ['序号', '姓名', '年龄', '省',"市","区"];
        let data = [['1', '2','3', '4', '5', '6']]
        data.unshift(_headers);  
             //表格数据
           // 数据格式为[["hello","223"],["22","23"]];
            let buffer = NXlSX.build([{name: "sheetName", data: data}]);
            // 返回buffer流到前端
            ctx.body = buffer
    }
}

module.exports = new CommonControls()